package com.github.postsanf.yinian.activity;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNLoginResponse;
import com.github.postsanf.yinian.huanxin.DemoHelper;
import com.github.postsanf.yinian.huanxin.db.DemoDBManager;
import com.github.postsanf.yinian.utils.DoSecretUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.SystemUtils;
import com.github.postsanf.yinian.utils.YNInviteSecret;
import com.github.postsanf.yinian.widget.SwipeBackActivity;
import com.github.postsanf.yinian.widget.SwipeBackLayout;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.LinkedHashMap;
import java.util.Map;

public class LoginWeChatActivity extends SwipeBackActivity implements View.OnClickListener {
    private ImageView iv_cloud_1;
    private ImageView iv_cloud_2;
    private ImageView iv_cloud_3;
    private ImageView iv_cloud_4;
    private ImageView iv_cloud_5;
    private ImageView iv_wx_login;
    private CheckBox cb_choose_agree;
    private TextView tv_olduser_login;
    private UMShareAPI mShareAPI = null;
    private SHARE_MEDIA platform = SHARE_MEDIA.WEIXIN;
    private TextView tv_protocol;
    private String userid = "";
    private String huanxinpassword = "";
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_choose2);
        registerBroadcast();
        mShareAPI = UMShareAPI.get(this);
        setDragEdge(SwipeBackLayout.DragEdge.BOTTOM);
        initView();
    }

    private void registerBroadcast() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.Exit);
        registerReceiver(MYReceiver, myIntentFilter);
    }

    BroadcastReceiver MYReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (TextUtils.equals(ACTIONs.Exit, intent.getAction())) {
                finish();
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(MYReceiver);
    }

    private void initView() {
        iv_cloud_1 = ((ImageView) findViewById(R.id.iv_cloud_1));
        iv_cloud_2 = ((ImageView) findViewById(R.id.iv_cloud_2));
        iv_cloud_3 = ((ImageView) findViewById(R.id.iv_cloud_3));
        iv_cloud_4 = ((ImageView) findViewById(R.id.iv_cloud_4));
        iv_cloud_5 = ((ImageView) findViewById(R.id.iv_cloud_5));
        iv_wx_login = ((ImageView) findViewById(R.id.iv_wx_login));
        cb_choose_agree = ((CheckBox) findViewById(R.id.cb_choose_agree));
        tv_olduser_login = ((TextView) findViewById(R.id.tv_olduser_login));
        tv_olduser_login.setTypeface(Typeface.createFromAsset(this.getAssets(), "fzqk.ttf"));
        tv_protocol = ((TextView) findViewById(R.id.tv_protocol));
        tv_protocol.setTypeface(Typeface.createFromAsset(this.getAssets(), "fzqk.ttf"));
        iv_wx_login.setOnClickListener(this);
        cb_choose_agree.setOnClickListener(this);
        tv_olduser_login.setOnClickListener(this);
        tv_protocol.setOnClickListener(this);
        initAnimation();
        mProgressDialog = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
        mProgressDialog.setTitle("");
        mProgressDialog.setMessage(CommonConstants.TIP_LOAD_LOGIN);
        mProgressDialog.setCanceledOnTouchOutside(false);
    }

    private void initAnimation() {
        ObjectAnimator ta1 = ObjectAnimator.ofFloat(iv_cloud_1, "translationX", 0, 140);
        ta1.setDuration(10000);
        ta1.setRepeatCount(Animation.INFINITE);
        ta1.setRepeatMode(ValueAnimator.REVERSE);
        ta1.start();
        ObjectAnimator ta2 = ObjectAnimator.ofFloat(iv_cloud_2, "translationX", 0, 140);
        ta2.setDuration(10000);
        ta2.setRepeatCount(Animation.INFINITE);
        ta2.setRepeatMode(ValueAnimator.REVERSE);
        ta2.start();
        ObjectAnimator ta3 = ObjectAnimator.ofFloat(iv_cloud_3, "translationX", 0, 140);
        ta3.setDuration(10000);
        ta3.setRepeatCount(Animation.INFINITE);
        ta3.setRepeatMode(ValueAnimator.REVERSE);
        ta3.start();
        ObjectAnimator ta4 = ObjectAnimator.ofFloat(iv_cloud_4, "translationX", 0, 140);
        ta4.setDuration(10000);
        ta4.setRepeatCount(Animation.INFINITE);
        ta4.setRepeatMode(ValueAnimator.REVERSE);
        ta4.start();
        ObjectAnimator ta5 = ObjectAnimator.ofFloat(iv_cloud_5, "translationX", 0, 140);
        ta5.setDuration(10000);
        ta5.setRepeatCount(Animation.INFINITE);
        ta5.setRepeatMode(ValueAnimator.REVERSE);
        ta5.start();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_wx_login:
                if (!cb_choose_agree.isChecked()) {
                    showToast("请先同意协议条款");
                    return;
                }
                if (!SystemUtils.isWeixinAvilible(LoginWeChatActivity.this)) {
                    showToast("请先安装微信");
                    return;
                }
                mProgressDialog.show();
                mShareAPI.doOauthVerify(LoginWeChatActivity.this, platform, umAuthListener);
                break;
            case R.id.tv_olduser_login:
                intent2Activity(LoginActivity.class);
                overridePendingTransition(R.anim.none_in, R.anim.slide_up_out);
                break;
            case R.id.tv_protocol:
                intent2Activity(AgreementActivity.class);
                break;
        }
    }

    // 授权监听
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            getUserInfo(platform);
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            showToast(getString(R.string.Wx_failed));
            mProgressDialog.dismiss();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            mProgressDialog.dismiss();
        }
    };

    // 授权回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
    }

    // 获取用户信息
    private void getUserInfo(SHARE_MEDIA platform) {
        mShareAPI.getPlatformInfo(LoginWeChatActivity.this, platform,
                new UMAuthListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {
                    }

                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                        Log.i("xjs", "user+onComplete==>" + map.toString());
                        try {
                            String openid = map.get(CommonConstants.PARAM_OPENID);
                            String nickname = map.get("screen_name");
                            String url = map.get("profile_image_url");
                            String sex = map.get("gender");
                            String province = "";
                            String city = "";
                            if (!StringUtils.isEmpty(map.get(CommonConstants.PARAM_PROVINCE))) {
                                province = map.get(CommonConstants.PARAM_PROVINCE);
                            }
                            if (!StringUtils.isEmpty(map.get(CommonConstants.PARAM_CITY))) {
                                city = map.get(CommonConstants.PARAM_CITY);
                            }
                            doLoginFromWx(openid, nickname, url, sex, province, city);
                        } catch (Exception e) {
                            showToast("授权出错，请重新授权");
                            mProgressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                        mProgressDialog.dismiss();
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i) {
                        mProgressDialog.dismiss();
                    }
                });
    }


    private String getVersionName(Context context) {
        String VersionName = null;
        try {
            VersionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return VersionName;
    }

    //登陆执行程序
    private void doLoginFromWx(String openid, String nickname, String url, String sex, String province, String city) {
        String UMENG_CHANNEL = SystemUtils.getAppStoreName(LoginWeChatActivity.this, "UMENG_CHANNEL");
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_OPENID, openid);
        mParam.put(CommonConstants.YNS_WECHATNICKNAME, nickname);
        mParam.put(CommonConstants.YNS_WECHATPIC, url);
        mParam.put(CommonConstants.YNS_WECHATSEX, sex);
        mParam.put(CommonConstants.YNS_PROVINCE, province);
        mParam.put(CommonConstants.YNS_CITY, city);
        mParam.put(CommonConstants.YNS_CHANELSOURCE, UMENG_CHANNEL);
        mParam.put(CommonConstants.YNS_APP_VERSION, getVersionName(LoginWeChatActivity.this));
        Log.i("xjs", "mParam.toString()==>" + mParam.toString());
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynLoginFromWX))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNLoginResponse resLogin = gson.fromJson(s, YNLoginResponse.class);
                        if (ReqUtils.isSuccess(resLogin.getCode())) {
                            // 存入录数据
                            SharedPreferences.Editor ed = application.getSp_login().edit();
                            ed.putString(getString(R.string.LID), DoSecretUtils.doSecretStr(String.valueOf(resLogin.getData().get(0).getUserid())));
                            ed.commit();
                            application.setCurID(resLogin.getData().get(0).getUserid());
                            userid = String.valueOf(resLogin.getData().get(0).getUserid());
                            try {
                                huanxinpassword = YNInviteSecret.decryptDES(String.valueOf(resLogin.getData().get(0).getPassword()), getResources().getString(R.string.UNKNOW_ID));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            doLoginHuanXin(userid, huanxinpassword);
                        } else {
                            mProgressDialog.dismiss();
                            showToast(resLogin.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        mProgressDialog.dismiss();
                        showToast(getString(R.string.YN_NET_LINK));
                    }
                });
        liteHttp.executeAsync(req);
    }


    private void doLoginHuanXin(String currentUsername, String currentPassword) {
        DemoDBManager.getInstance().closeDB();
        DemoHelper.getInstance().setCurrentUserName(currentUsername);
        EMClient.getInstance().login(currentUsername, currentPassword, new EMCallBack() {
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                boolean updatenick = EMClient.getInstance().updateCurrentUserNick(
                        BaseApplication.currentUserNick.trim());
                if (!updatenick) {
                    Log.e("LoginActivity", "update current user nick fail");
                }
                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
                CloseMainActivity();
                mProgressDialog.dismiss();
                sendBroadcast(new Intent(ACTIONs.actionCloseactivity));
                intent2Activity(MainActivity.class);
                finish();
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(final int code, final String message) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        mProgressDialog.dismiss();
                        Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void CloseMainActivity() {
        if (getSharedPreferences("OURINFO", MODE_PRIVATE).getBoolean("active", false)) {
            if (MainActivity.myMainActivity != null &&
                    !MainActivity.myMainActivity.isFinishing()) {
                MainActivity.myMainActivity.finish();
            }
        }
    }

    private long fristTime;

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        fristTime = System.currentTimeMillis();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        Intent intent = new Intent(ACTIONs.record);
        intent.putExtra("key", "login_3");
        intent.putExtra("value", new Long(System.currentTimeMillis() - fristTime).intValue());
        sendBroadcast(intent);
    }
}
